package com.cuit.controller;

import com.cuit.doamin.Admin;
import com.cuit.doamin.User;
import com.cuit.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 测试
     *
     * @return
     */
    @RequestMapping("/test")
    public ModelAndView testSpringMVC() {
        ModelAndView mv = new ModelAndView();
        List<Admin> all = adminService.findAll();
        for (Admin admin : all) {
            System.out.println(admin);
        }
        mv.setViewName("pages/success");
        return mv;
    }

    /**
     * 用户登录
     *
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView login(String name, String pwd, String type, HttpServletRequest request) {

        ModelAndView mv = new ModelAndView();

        if (type.equals("user")) {

            User user = new User();
            user.setU_name(name);
            user.setU_pwd(pwd);
            User u = adminService.findByUname(user);

            if (u != null) {
                request.getSession().setAttribute("user", user);
                mv.setViewName("user/frame");
            } else {
                mv.setViewName("pages/error");
            }
        } else if (type.equals("admin")) {

            Admin admin = new Admin();
            admin.setA_name(name);
            admin.setA_pwd(pwd);
            Admin a = adminService.findByAname(admin);

            if (a != null) {
                request.getSession().setAttribute("admin", admin);
                mv.setViewName("admin/frame");
            } else {
                mv.setViewName("pages/error");
            }
        } else {
            mv.setViewName("pages/error");
        }
        return mv;
    }

    /**
     * 修改密码
     *
     * @return
     */
    @RequestMapping("/updatePwd")
    public ModelAndView updatePwd(String password, HttpServletRequest request) {

        ModelAndView mv = new ModelAndView();
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        int i = adminService.updatePwd(admin.getA_name(), password);
        if (i == 1) {
            mv.setViewName("pages/success");
        } else {
            mv.setViewName("pages/error");
        }
        return mv;
    }

}
